<template>
	<van-popup v-model:show="popupShow" round closeable position="bottom" :style="{ height: '92%' }" class="sku-popup" @click-close-icon="resetSelected" @click-overlay="resetSelected">
		<div class="header-wrap">
			<div class="flex">
				<van-icon name="send-gift" class="txt-primary" />
				<div class="mgl10">
					<div class="font-14 mgb5">{{package.packageName}}</div>
					<div class="font-12 txt-unicom" @click="showDialog({message:package.packageDesc})">
						<span v-if="minBuyCount>1" class="txt-gray font-12 mgr10">{{minBuyCount}}件起批</span>
						<span class="txt-unicom">查看详细介绍 <van-icon name="arrow"/></span>
					</div>
				</div>
			</div>
		</div>
		<div class="main-sku-wrap" v-if="package">
			<van-cell-group inset v-for="(group,i) in skuGroup.groupList">
				<van-cell class="gds-label">
					<template #title>
						<b class="font-14">组合{{i+1}}</b>
					</template>
					搭配: <b class="txt-primary">{{group.ratio}}</b>件/套
				</van-cell>
				<template v-for="(gds) in group.gdsList">
					<van-cell class="gds-label">
						<template #title>
							<div class="title van-ellipsis">{{gds.gdsName}}</div>
						</template>
						<span class="txt-primary" v-if="gds.minPrice!==gds.maxPrice"><small>￥</small>{{fen2Yuan(gds.minPrice)}} ~ <small>￥</small>{{fen2Yuan(gds.maxPrice)}}</span>
						<span class="txt-primary" v-else><small>￥</small>{{fen2Yuan(gds.minPrice)}}</span>
					</van-cell>
					<van-cell v-for="(item) in gds.skus" class="sku-wrap">
						<template #title>
							<van-badge v-if="item.skuImg" :content="item.selectNum" :show-zero="false">
								<img alt="" :src="item.skuImg" @click="imgPreview(item.skuImg)"/>
							</van-badge>
							<van-badge v-else :content="item.selectNum" :show-zero="false"/>
							<div class="col-main">
								<div>
									<template v-for="(para,k) in item.params" key="para.vId">
										<span v-if="k>0" class="pre">&middot;</span>
										<span>{{para.vName}}</span>
									</template>
								</div>
								<div class="sec-floor">
									<span class="txt-primary">￥{{skuPrice(item.skuPrice)}}</span> <span class="mgr5 mgl5">|</span>
									<template v-if="item.stockAmount>0">库存{{item.stockAmount}}</template>
									<template v-else>缺货</template>
								</div>
							</div>
						</template>
						<template v-if="i===0">
							<van-stepper :disabled="!item.stockAmount||item.stockAmount===0" integer :default-value="0" input-width="1rem"
										 v-model="item.selectNum" :min="0" :max="item.stockAmount" @change="handleChange"
										 :step="gds.skus.length===1? group.ratio:1"
							/>
						</template>
						<template v-else>
							<van-stepper :disabled="!item.stockAmount||item.stockAmount===0" integer :default-value="0" input-width="1rem"
										 v-model="item.selectNum" :min="0" :max="item.stockAmount" @change="handleChange"
										 :step="gds.skus.length===1? group.ratio:1"
										 :before-change="function(val:number){
											 let abs=val-item.selectNum;if(abs<=0)	return true; else if(abs>group.waitNum)return false; return true;
										 }"
							/>
						</template>
					</van-cell>
				</template>
				<van-cell class="gds-label">
					<template #title><span class="txt-gray">已选 <span class="txt-primary">{{group.selectNum}}</span> 件</span></template>
					<template #value>
						<div v-if="group.waitNum>=0">待选 <span class="txt-unicom">{{group.waitNum}}</span> 件</div>
						<div v-else>超出 <span class="txt-unicom">{{-1*group.waitNum}}</span> 件</div>
					</template>
				</van-cell>
			</van-cell-group>
		</div>
		<div class="sheet-stat">
			<div>已选 <span class="txt-primary">{{totalCount}}</span> 件</div>
			<div>总额(不含运费)：<span class="txt-primary">￥<span class="font-16">{{totalPrice}}</span></span></div>
		</div>
		<div class="sheet-btn-wrap">
			<van-button type="warning" v-if="btnCartShow" :disabled="actionDisable" @click="handleAddCartClick">加采购车</van-button>
			<van-button type="primary" v-if="btnBugShow" :disabled="actionDisable" @click="handleBuyClick">立即订购</van-button>
		</div>
	</van-popup>
</template>
<style lang="scss" scoped>
.header-wrap{
	padding:10px 16px;border-bottom:1px solid var(--van-cell-border-color);
	--van-tag-primary-color:var(--van-primary-color);
	.tag{margin-left:4px;padding:0 3px;}
	&>.flex{
		height:36px;
		&>.van-icon{font-size:24px}
	}
	.price{
		height:24px;line-height:24px;
	}
}
.sheet-btn-wrap{
	.van-button{border-radius:0;font-weight:bold;display:block;flex:1;}
	:deep(.van-button--primary){
		background: linear-gradient(90deg, #fff -250%, var(--van-primary-color) 100%);
	}
	:deep(.van-button--warning){
		background: var(--van-action-bar-button-warning-color);
	}
	.van-button:first-child{
		border-top-left-radius: 22px;border-bottom-left-radius: 22px;
	}
	.van-button:last-child{
		border-top-right-radius: 22px;border-bottom-right-radius: 22px;
	}
}
.sheet-stat{
	height:33px;background: var(--white-color);display:flex;align-items: center; justify-content: space-between;
	border-top:1px solid var(--van-cell-border-color); font-size:12px;
	position:absolute;bottom:calc(50px + env(safe-area-inset-bottom)); left:0;right:0;padding:4px 16px 0;
	&>div:first-child{ color:var(--font-third-color);}
}
.main-sku-wrap{
	max-height:calc(92vh - 140px); overflow-x:hidden; overflow-y:auto;
	--van-cell-horizontal-padding:10px;--van-padding-md:10px;
	.gds-label{
		font-size:13px;
		.title{width:52vw;}
		:deep(.van-cell__title){flex:1.5;}
		small{font-size:80%;}
	}
	:deep(.van-badge__wrapper){display:block;}
	:deep(.van-badge--top-right){ transform: translate(0,-50%); }
	.sku-wrap {
		align-items:center;
		:deep(.van-cell__title){
			flex:2.2;line-height:20px; display:flex; align-items:center; font-size:12px; max-height:50px;
		}
		img { width:48px; height:48px;display:block; overflow:hidden; border-radius:4px;}
		.col-main {padding-left:8px;line-height:18px;}
		.pre{margin:0 2px}
		.sec-floor{ font-size:12px; color:var(--font-third-color); }
	}
	.btn-preview{
		display:flex;width:26px;height:26px;background:rgba(0,0,0,.3);align-items:center;justify-content:center;
		color:var(--white-color);font-size:20px;position:absolute; bottom:32px;right:4px; border-radius:4px;
	}
}
</style>
<script lang="ts" setup>
import {showDialog, showImagePreview} from 'vant'
import {GdsPackage,} from "@/types";
import {fen2Yuan} from "@/utils/validate";
//props
const props=defineProps<{
	package:GdsPackage,
	minBuyCount:Number,
}>()
//emits
const emit = defineEmits<{
	(e: 'add-cart-click', skuSelected: any): void
	(e: 'buy-click', skuSelected: any): void
}>()

//data
const popupShow=ref(false)
const btnCartShow=ref(false)
const btnBugShow=ref(false)
const previewImgList:string[] = []

//每个初级属性tab下，各有哪些sku单品信息
const skuGroup=reactive<any>({
	//propId:'',
	groupList:<Array<GdsPackage>>[],
})
const totalCount=ref(0) //已选的单品件数总数
const totalPrice=ref(0) //已选的单品总额

//computed
//计算属性：已选的单品价格显示
const skuPrice = computed(()=>{
	return function(initPrice:number){
		if(!props.package)	return 0;
		return fen2Yuan(initPrice)
	}
})

//初始化 begin
//console.log(props.package)
//初始化 end

//computed
const actionDisable=computed(()=>{
	for(let group of skuGroup.groupList){
		if(group.waitNum!==0)	return true
	}
	return totalCount.value===0
})

//methods
const reloadGroup=()=>{
	if(props.package.groupList ){

		//初始化常规则单品信息
		skuGroup.groupList.splice(0,skuGroup.groupList.length)
		previewImgList.splice(0,previewImgList.length)
		for(let i=0;i<props.package.groupList.length;++i){
			let group = Object.assign({},props.package.groupList[i])
			group.selectNum=0
			group.waitNum=i===0? group.ratio:0
			for(let gds of group.gdsList){
				for(let sku of gds.skus){
					sku.selectNum=0
					if(sku.skuImg)previewImgList.push(sku.skuImg)
				}
			}
			skuGroup.groupList.push(group)
		}
		//console.log(skuGroup)
	}
}
const displaySkuSheet =(type:string|undefined)=>{
	popupShow.value=true
	if(!type){
		btnCartShow.value=true
		btnBugShow.value=true
	}else if('0'===type){
		btnCartShow.value=true
		btnBugShow.value=false
	}else{
		btnCartShow.value=false
		btnBugShow.value=true
	}
}
const hideSkuSheet =()=>{popupShow.value=false}

//重置清空当前sku弹框里的选择
const resetSelected=()=>{
	for(const group of skuGroup.groupList){
		for(const gds of group.gdsList){
			for(const item of gds.skus){
				item.selectNum=0
			}
		}
	}
}


//单品选择数量改变的事件
const handleChange = () => {
	//console.log(cur)
	let allCount=0,allPrice=0,i=0
	for(let group of skuGroup.groupList){
		let numSelect=0,moneySelect=0
		for(let gds of group.gdsList){
			for(let sku of gds.skus as any[]){
				numSelect += sku.selectNum as number
				moneySelect += sku.skuPrice*sku.selectNum
			}
		}
		group.selectNum = numSelect
		if(i===0){
			//如果是第一个，即主商品
			if(numSelect===0){
				group.waitNum = group.ratio
			}else{
				group.waitNum = numSelect%group.ratio
			}
		}else{
			//如果不是第一个，即套包捆绑的商品
			let mainNum = Math.ceil(skuGroup.groupList[0].selectNum/skuGroup.groupList[0].ratio)
			//group.waitNum = waitNum<0? 0:waitNum
			group.waitNum = mainNum * group.ratio - group.selectNum
		}
		allCount += numSelect
		allPrice += moneySelect
		++i
	}
	totalCount.value=allCount
	totalPrice.value=fen2Yuan(allPrice)
}

//sku图片预览
const imgPreview=(vImg:string)=>{
	let index = previewImgList.findIndex((item)=> item===vImg)
	//console.log(previewImgList,index)
	if(index>-1){
		showImagePreview({
			images: previewImgList, startPosition: index,
		});
	}
}
//将已挑选的所有sku信息提取出来
const getSkuSelected=()=>{
	let skuSelected={
		totalCount: totalCount.value,
		totalPrice: totalPrice.value,
		skus:<any[]>[],
	}
	for(let group of skuGroup.groupList) {
		for (let gds of group.gdsList as any[]) {
			for (let sku of gds.skus as any[]) {
				if(sku.selectNum>0){
					skuSelected.skus.push(Object.assign({},sku))
				}
			}
		}
	}
	return skuSelected
}

//加采购车按钮被点击时的事件
const handleAddCartClick=()=>{
	//if(!checkTao())	return
	popupShow.value=false
	emit('add-cart-click',getSkuSelected())
	resetSelected()
}
//订购按钮被点击时的事件
const handleBuyClick=()=>{
	//if(!checkTao())	return
	popupShow.value=false
	emit('buy-click',getSkuSelected())
	resetSelected()
}

//提交前，先检查套包的各商品搭配套数是否一致
// const checkTao=()=>{
// 	if(skuGroup.groupList.length===0)	return false
// 	let tao = skuGroup.groupList[0].selectNum/skuGroup.groupList[0].ratio
// 	for(let i=1;i<skuGroup.groupList.length;++i){
// 		let group =skuGroup.groupList[i]
// 		if(group.selectNum/group.ratio !== tao){
// 			showToast('商品：'+group.gdsName+' 的搭配套数与主商品预选的套数不一致，请先调整搭配套数')
// 			return false
// 		}
// 	}
// 	return true
// }

defineExpose({
	//data
	totalCount,totalPrice,
	//methods
	reloadGroup,displaySkuSheet,hideSkuSheet,resetSelected,
})
</script>